package com.mk.ancientrpcstarter.service;

import com.mk.ancientrpcstarter.client.TcpClient;
import com.mk.ancientrpcstarter.entity.RpcRequest;
import com.mk.ancientrpcstarter.enums.CommandEnum;
import com.mk.ancientrpcstarter.logging.Log;
import com.mk.ancientrpcstarter.logging.LogFactory;
import com.mk.ancientrpcstarter.protocol.RpcProtocol;
import com.mk.ancientrpcstarter.util.ByteConverter;

/**
 * @description:
 * @author: M.K
 * @date: 2021/12/22
 */

public class RequestService {

    private Log log = LogFactory.getLog(RequestService.class);

    public int addObject(RpcRequest request) throws Exception {
        TcpClient client = TcpClient.GetInstance();
        try {
            client.init();
        } catch (Exception e) {
            log.error("init rpc client error.", e);
        }
        //构造请求数据
        RpcProtocol rpcReq = new RpcProtocol();
        rpcReq.setCmd(CommandEnum.REQUEST.getCode());
        rpcReq.setVersion(0x01);
        rpcReq.setMagicNum(RpcProtocol.CONST_CMD_MAGIC);
        byte[] body = RpcProtocol.object2Bytes(request);
        rpcReq.setBodyLen(body.length);
        rpcReq.setBody(body);

        //序列化
        byte[] reqData = rpcReq.generateByteArray();

        //发送请求
        client.sendData(reqData);

        //接收请求结果
        byte[] recvData = client.recvData();

        //反序列化结果
        RpcProtocol rpcResp = new RpcProtocol();
        rpcResp.byteArrayToRpcHeader(recvData);
        return ByteConverter.bytesToInt(rpcResp.getBody(), 0);
    }
}
